package com.azh.server.util;

import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

import com.google.common.primitives.Bytes;

/**
 * @author zhaozhenhang <zhaozhenhang@kuaishou.com>
 * Created on 2022-04-24
 */
public class Parser {

    public static byte[] shortToByte(short value) {
        return ByteBuffer.allocate(Short.SIZE / Byte.SIZE).putShort(value).array();
    }

    public static short parseShort(byte[] bytes) {
        /*
         * @deprecated wrap 是将byte[] 保证成一个buffer对象
         */
        ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, 2);
        return buffer.getShort();
    }

    public static byte[] intToByte(int value) {
        return ByteBuffer.allocate(Integer.SIZE / Byte.SIZE).putInt(value).array();
    }

    public static int parseInt(byte[] bytes) {
        ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, 4);
        return buffer.getInt();
    }

    public static byte[] longToByte(long value) {
        return ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(value).array();
    }

    public static long parseLong(byte[] bytes) {
        ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, 8);
        return buffer.getLong();
    }

    public static byte[] stringToByte(String msg) {
        byte[] bytes = intToByte(msg.length());
        return Bytes.concat(bytes, msg.getBytes(StandardCharsets.UTF_8));
    }

    public static ParserStr parserStr(byte[] bytes) {
        int len = parseInt(Arrays.copyOf(bytes, 4));
        String msg = new String(Arrays.copyOfRange(bytes, 4, 4 + len));
        return new ParserStr(msg, len + 4);
    }

    public static long strToUUID(String msg) {
        long seed = 13331;
        long res = 0;
        for (byte b : msg.getBytes()) {
            res = res * seed + (long) b;
        }
        return res;
    }
}
